//
//  HeaderUtil.m
//  YiJuZhangShou
//
//  Created by 冷悦 on 16/3/3.
//  Copyright © 2016年 Uranus. All rights reserved.
//

#import "HeaderUtil.h"
#import "AESUtil.h"
#import "AppContext.h"
#import "SyncTimer.h"
#import "NSString+SHA.h"

@implementation HeaderUtil

#pragma mark - Private
+ (NSString *)genIVParameter:(NSInteger)bitNum{
    NSString *ivParameter = [[NSString alloc]init];
    
    for (int i = 0; i < bitNum; i++) {
        int number = arc4random() % 36;
        if (number < 10) {
            int figure = arc4random() % 10;
            NSString *tempString = [NSString stringWithFormat:@"%d", figure];
            ivParameter = [ivParameter stringByAppendingString:tempString];
        }else {
            int figure = (arc4random() % 26) + 97;
            char character = figure;
            NSString *tempString = [NSString stringWithFormat:@"%c", character];
            ivParameter = [ivParameter stringByAppendingString:tempString];
        }
    }
    
    return ivParameter;
}

+ (NSString *)getParam:(NSString *)paramName inDataTask:(NSURLSessionDataTask *)task{
    NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
    NSDictionary *allHeaderFields = response.allHeaderFields;
    NSString *value = [allHeaderFields objectForKey:paramName];
    
    return value;
}

#pragma mark - Public
+ (NSString *)genIVParameter{
    NSString *ivParameter = [HeaderUtil genIVParameter:16];
    
    return ivParameter;
}

+ (void)storeAppToken:(NSURLSessionDataTask *)task withParams:(NSDictionary *)params{
    NSString *iv = [self getParam:@"iv" inDataTask:task];
    NSString *encriptToken = [params objectForKey:@"encriptToken"];
    NSString *token = [AESUtil decryptAESData:encriptToken
                                      withKey:@"hr3JT0R4HA8A5Uty"
                                        andIV:iv];
    [AppContext sharedInstance].appToken = token;
}

+ (void)generateSHA256Header:(AFHTTPSessionManager *)manager{
    NSString *token = [AppContext sharedInstance].appToken;
    
    if (token != nil) {
        token = [token sha256];
        long long timestamp = [SyncTimer sharedInstance].systemTimeMillis;
        NSInteger seconds = timestamp / 1000 % 60;
        NSInteger time1 = seconds / 10;
        NSInteger addNum = seconds % 10;
        NSInteger pos = time1 * addNum;
        NSMutableString *encriptToken = [NSMutableString stringWithFormat:token, nil];
        [encriptToken deleteCharactersInRange:NSMakeRange(pos, 1)];
        [encriptToken insertString:[NSString stringWithFormat:@"%ld",(long)addNum]
                           atIndex:pos];
        DDLogInfo(@"token:%@",encriptToken);
        [manager.requestSerializer setValue:encriptToken forHTTPHeaderField:@"token"];
        [manager.requestSerializer setValue:[NSString stringWithFormat:@"%lld",timestamp] forHTTPHeaderField:@"timestamp"];
    }
}

@end
